# -*- coding: utf-8 -*-
"""
author:码同学 极光
date:2023-02-04
desc: 
sample: 
"""
import logging
import os
import random
import time
import gevent
from locust import HttpUser, task, constant, FastHttpUser, events
from locust.runners import WorkerRunner, STATE_STOPPING, STATE_STOPPED, STATE_CLEANUP


#如果发现指标不合适，自动停止压测，发邮件
from util import get_project_path, getcsv_listdict
from utils.EamilUtils import EmailUtils

is_quitting = False
#指标不满足自动停止
def sendEmail(title, msg):
    emailUtils = EmailUtils(host="smtp.163.com", user="testfan2@163.com", password="MSQOTDVQPMKSRZZS")
    # 发送一封邮件
    emailUtils.send(title=title, Context=msg, to_addrs="279313259@qq.com")


def checker(environment, **kw):
    global is_quitting
    while not environment.runner.state in [STATE_STOPPING, STATE_STOPPED, STATE_CLEANUP]:
        print("checker-----")
        time.sleep(1) #需要等待系统启动注册
        if environment.runner.stats.total.fail_ratio > 0.01:
            logging.error("Test failed due to failure ratio > 1%")
            is_quitting = True
        elif environment.stats.total.avg_response_time > 100:
            logging.error(f"Test failed due to average response time ratio > 200ms,quitting")
            is_quitting = True
        elif environment.stats.total.get_response_time_percentile(0.95) > 300:
            logging.error(f"Test failed due to 95th percentile response time > 300, quitting")
            is_quitting = True

        if is_quitting:
            error_msg={}
            error_msg['错误率']= environment.runner.stats.total.fail_ratio
            error_msg['平均响应时间'] = str(int(environment.stats.total.avg_response_time))+"ms"
            error_msg['top95'] = str(int(environment.stats.total.get_response_time_percentile(95)))+"ms"
            print(error_msg)
            sendEmail(title='登陆压测指标不满足需求', msg="当前指标："+ error_msg.__str__())
            environment.runner.quit()
            return


@events.init.add_listener
def on_locust_init(environment, runner, **_kwargs):
    if not isinstance(environment.runner, WorkerRunner):
        gevent.spawn(checker, environment)

class LoginParmas(HttpUser):
    host = 'http://82.156.74.26:9088/pinter'
    data_list = getcsv_listdict(os.path.join(get_project_path(),"files","user.csv"))

    @task  # locust
    def login(self):
        url = self.host + '/com/login'
        randomdata = random.choice(LoginParmas.data_list)
        print(randomdata)
        data = {"userName": randomdata['username'], 'password': randomdata['pwd']}
        with self.client.post(url=url, data=data, catch_response=True, timeout=5) as response:
            #if response.json()['message'] == 'success':
            try:
                if response.json().get('message') == 'success':
                    response.success()
                else:
                    response.failure(response.json())
            except Exception as e:
                response.failure(e)



if __name__ == '__main__':
    os.system('locust -f Login参数化.py')
